//
//  BCSettingViewController.swift
//  BarCode
//
//  Created by xxcao on 2017/3/29.
//  Copyright © 2017年 MobileArtisan. All rights reserved.
//

import UIKit


struct CellModel {
    var title: String?
    var detail: String?
    var indexPath: NSIndexPath?
    
    init(tmpTitle: String, tmpDetail: String, index: NSIndexPath) {
        title = tmpTitle
        detail = tmpDetail
        indexPath = index
    }
}


class BCSettingViewController: BCFatherViewController {
    
    lazy var tableView : UITableView = UITableView(frame: CGRect.zero, style: .plain).then {
        $0.backgroundColor = self.bgColor
        $0.delegate = self
        $0.dataSource = self
        self.view.addSubview($0)
        $0.snp.makeConstraints({ make in
            make.edges.equalToSuperview()
        })
        $0.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        $0.separatorColor = UIColor(white: 0.5, alpha: 0.3)
    }
    
    lazy var dataSource = [
        CellModel(tmpTitle: "姓名", tmpDetail: gUser.full_name!, index: NSIndexPath(row: 0, section: 0)),
        CellModel(tmpTitle: "账号", tmpDetail: gUser.user_name!, index: NSIndexPath(row: 1, section: 0)),
        CellModel(tmpTitle: "工号", tmpDetail: gUser.staff_code!, index: NSIndexPath(row: 2, section: 0)),
        CellModel(tmpTitle: "邮箱", tmpDetail: gUser.email!, index: NSIndexPath(row: 3, section: 0)),
        CellModel(tmpTitle: "修改密码", tmpDetail: "", index: NSIndexPath(row: 0, section: 1)),
        CellModel(tmpTitle: "版本检测", tmpDetail: appVersion,index: NSIndexPath(row: 0, section: 2)),
        CellModel(tmpTitle: "", tmpDetail: "", index: NSIndexPath(row: 0, section: 3))
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "设置"
        customBackBarItem()
        Common.removeExtraCellLines(TableView: tableView)
    }
    
    func exitBarCode() {
        let alert = UIAlertView(title: "提示", message: "确定要退出吗？", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
        alert.delegate = self
        alert.show()
    }
}

extension BCSettingViewController: UITableViewDataSource {
    public func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 4
        }
        return 1
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentify = "CellIdentify"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentify)
        if cell == nil {
            cell = Bundle.main.loadNibNamed("SettingCell", owner: self, options: nil)?.first as? UITableViewCell
        }
        var index:Int = -1
        if indexPath.section == 0 && indexPath.row == 0 {
            index = 0
        }
        else if indexPath.section == 0 && indexPath.row == 1 {
            index = 1
        }
        else if indexPath.section == 0 && indexPath.row == 2 {
            index = 2
        }
        else if indexPath.section == 0 && indexPath.row == 3 {
            index = 3
        }
        else if indexPath.section == 1 {
            index = 4
        } else if indexPath.section == 2 {
            index = 5
        } else if indexPath.section == 3 {
            index = 6
        }
        (cell as! SettingCell).loadCellData(obj: dataSource[index])
        (cell as! SettingCell).exitBlock = {(cell)->(Void) in
            self.exitBarCode()
        }
        return cell!
    }
}

extension BCSettingViewController: UITableViewDelegate {
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 1 {
            let modifyPasswordVC = BCPasswordViewController(nibName: "BCPasswordViewController", bundle: nil)
            navigationController?.pushViewController(modifyPasswordVC, animated: true)
        }
        if indexPath.section == 2 {
            SVProgressHUD.show()
            BmobManager.checkAppVersion { (res, status) -> (Void) in
                if status == .NRSSuccess {
                    if !isHasNewVersion {
                        SVProgressHUD.showSuccess(withStatus: "当前已是最新版本")
                        SVProgressHUD.dismiss(withDelay: 1.5)
                        return
                    }
                    SVProgressHUD.dismiss()
                    let appDelegate = AppDelegate()
                    appDelegate.checkApp(serVersion: serverVersion)
                } else {
                    SVProgressHUD.showSuccess(withStatus: "版本检测失败")
                    SVProgressHUD.dismiss(withDelay: 1.5)
                }
            }
        }
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 3 {
            return UIScreen.main.bounds.height - 64 * 2 - 6 * 60 - 2 * 20
        }
        return 60
    }
    
    public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section != 0 {
            return 20
        }
        return 0.01
    }
    
    public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = bgColor
        return view
    }
}

extension BCSettingViewController: UIAlertViewDelegate {
    public func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
        if buttonIndex == 1 {
            BmobManager.logout {_,_ in}
            //删除密码
            UserDefaults.standard.removeObject(forKey: UserDefaultsKey.userPsd.rawValue)
            let shake = CABasicAnimation(keyPath: "transform.rotation.z")
            shake.fromValue = NSNumber(value: -.pi / (4.0 * 24.0))
            shake.toValue = NSNumber(value: .pi / (4.0 * 24.0))
            shake.duration = 0.1
            shake.autoreverses = true
            shake.repeatCount = 6
            let window = view.window
            window?.layer.add(shake, forKey: "shakeAnimation")
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5, execute: {
                exit(0)
            })
        }
    }
}
